package com.chiry.buyer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chiry.buyer.pojo.Category;
import com.chiry.buyer.service.goods.CategoryService;
import com.chiry.buyer.vo.CategoryVO;
import com.chiry.shop.goods.CategoryMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author fyx
 * @version 1.0
 * @date 2021/12/17 14:15
 */
@DubboService(version = "1.0.0",interfaceClass = CategoryService.class)
public class CategoryServiceImpl implements CategoryService {
    @Resource
    CategoryMapper categoryMapper;

    @Override
    public List<CategoryVO> findCategoryTree(Long parentId) {
        return categoryTree(parentId);
    }

    private List<CategoryVO> categoryTree(Long parentId) {
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        categoryLambdaQueryWrapper.eq(Category::getStatus, 0);
        List<Category> categories = categoryMapper.selectList(categoryLambdaQueryWrapper);
        List<CategoryVO> categoryVOS = copyList(categories);
        ArrayList<CategoryVO> categoryVOTree = new ArrayList<>();
        for (CategoryVO categoryVO : categoryVOS) {
            if (categoryVO.getParentId().equals(parentId)){
                categoryVOTree.add(categoryVO);
                addAllChildren(categoryVO,categoryVOS);
            }
        }
        return categoryVOTree;
    }


// 使用递归的方法
    private void addAllChildren(CategoryVO categoryVO, List<CategoryVO> categoryVOS) {
        List<CategoryVO> categoryVOList = new ArrayList<>();
        for (CategoryVO vo : categoryVOS) {
            if (vo.getParentId().equals(categoryVO.getId())){
                categoryVOList.add(vo);
                addAllChildren(vo,categoryVOS);
            }
        }
        categoryVO.setChildren(categoryVOList);
    }

    private List<CategoryVO> copyList(List<Category> categories) {
        ArrayList<CategoryVO> categorieVOs = new ArrayList<CategoryVO>();
        for (Category category : categories) {
            CategoryVO categoryVO = new CategoryVO();
            categorieVOs.add(copy(category,categoryVO));
        }
        return categorieVOs;
    }

    private CategoryVO copy(Category category, CategoryVO categoryVO) {
        BeanUtils.copyProperties(category,categoryVO);
        return categoryVO;
    }

}
